require(['jquery', 'layer', 'jquery.nestable', 'jquery.icheck', 'main'], function($, layer) {
    //初始化layer
    layer.config({
        path: '/components/layer/3.0.1/'
    });
    
	var updateOutput = function(e) {
		var list = e.length ? e : $(e.target), output = list.data("output");
		if(window.JSON) {
			output.val(window.JSON.stringify(list.nestable("serialize")))
		} else {
			output.val("浏览器不支持")
		}
	};
	
	// 初始化js
	$("#nestable").nestable({group: 1});
	
	// 全部展开/关闭
	$("#nestable-menu").on("click", function(e) {
		var target = $(e.target), action = target.data("action");
		if(action === "expand-all") {
			$(".dd").nestable("expandAll")
		}
		if(action === "collapse-all") {
			$(".dd").nestable("collapseAll")
		}
	})
	
	// 排序处理
	$('#nestable').on('change', function(e) {
		updateOutput($("#nestable").data("output", $("#nestable-output")));
		var list = e.length ? e : $(e.target), output = list.data("output");
		if(window.JSON) {
			output.val(window.JSON.stringify(list.nestable("serialize")));
			var sortInfo = window.JSON.stringify(list.nestable("serialize"));
			$.ajax({
	            type: "POST",
	            url: "sort",
	            data: sortInfo,
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (d) {
	                if(d.success){
						layer.msg('修改排序成功!',{icon:1,time:1000});
						return;
					}
					layer.msg(d.message,{icon:5,time:1000});
	            }
	        });
		} else {
			output.val('浏览器不支持');
			alert('浏览器不支持');
		}
	});
	
	// 增加菜单
	$('#nestable').delegate('.add', 'click', function(){
		$this = $(this);
		var pid = $(this).data('pid');
		var sort = $(this).data('sortNo');
		var title = '添加菜单';
		var url = 'add?pid=' + pid + '&sort=' + sort;
		layerShow(title,url,"800","500");
	});
	
	// 按钮事件
	$('#nestable').delegate('.edit-menus span', 'click', function(){
		var id = title = url = null;
		id = $(this).parents('li').data('id');
		if($(this).hasClass('glyphicon-search')){
			title = '菜单详情';
			url = 'view?id=' + id;
			layerShow(title, url);
		} else if($(this).hasClass('glyphicon-edit')){
			title = '编辑菜单';
			url = 'edit?id=' + id;
			layerShow(title, url);
		} else if($(this).hasClass('glyphicon-trash')){
			var $this = $(this);
			url = 'del';
			layer.confirm('确认删除吗?\n 如有子菜单将一并删除',function(index){
				$.post(url, {"id": id}, function(d){
					if(d.success){
						$this.parent().parent().parent().remove();
						layer.msg('已删除!',{icon:1,time:1000});
						return;
					}
					layer.msg('删除失败!',{icon:5,time:1000});
				},"json");
			});
		}
	});
});